package com.cgnpc.scp.hr.service.impl;

import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.result.ApiResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cgnpc.cuddemo.utils.IDHelper;
import com.cgnpc.framework.service.IBpmCenterService;
import com.cgnpc.framework.userinfo.CurrentUser;
import com.cgnpc.scp.common.exception.ScpException;
import com.cgnpc.scp.common.pojo.UserInfo;
import com.cgnpc.scp.common.utils.StringUtil;
import com.cgnpc.scp.hr.mybatis.entity.HrDeployPlan;
import com.cgnpc.scp.hr.mybatis.entity.HrProcessRecord;
import com.cgnpc.scp.hr.mybatis.mapper.client.HrDeployPlanMapper;
import com.cgnpc.scp.hr.mybatis.mapper.client.HrProcessRecordMapper;
import com.cgnpc.scp.hr.service.HrDeployPlanService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("hrDeployPlanService")
public class HrDeployPlanServiceImpl implements HrDeployPlanService {

    @Autowired
    IBpmCenterService bpmCenterService;

    @Autowired
    private CurrentUser currentUser;

    @Autowired
    private HrDeployPlanMapper hrDeployPlanMapper;

    @Autowired
    private HrProcessRecordMapper hrProcessRecordMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HrDeployPlan savePlan(Map<String, Object> params) throws Exception {
        Map<String, Object> win = (Map<String, Object>)params.remove("plan");
        HrDeployPlan hrDeployPlan = saveOrUpdatePlan(win);

        params.put("next_deal_name", JSONArray.parseArray(JSON.toJSONString(params.remove("next_deal_name"))));
        Object copygive = params.remove("copygive");
        if(copygive != null && !"".equals(copygive)){
            params.put("copygive",JSONArray.parseArray(JSON.toJSONString(copygive)));
        }
        params.put("win", JSON.parseObject(JSON.toJSONString(win)));
        params.put("folio", hrDeployPlan.getFolio());
        ApiResult apiResult = null;
        //判断是否为保存草稿
        params.put("appFormId", hrDeployPlan.getId());
        if("1".equals(params.get("isSaveDraft"))){
            if(!"1".equals(params.get("isModifyDraft"))){
                bpmCenterService.addDraft(params);
            }
        }else{
            //System.out.println("流程启动---");
            apiResult = bpmCenterService.startProcess(params);
            //System.out.println("result--" +apiResult);
        }
        return hrDeployPlan;
    }

    private HrDeployPlan saveOrUpdatePlan(Map<String, Object> params) throws Exception {
        HrDeployPlan hrDeployPlan = new HrDeployPlan();
        params.remove("createTime");
        params.remove("lastUpdateTime");
        BeanUtils.populate(hrDeployPlan, params);

        Date date = new Date();
        UserInfo currentUserDetail = currentUser.getCurrentUserDetail();
        hrDeployPlan.setLastUpdateTime(date);
        hrDeployPlan.setLastUpdateUser(currentUserDetail.getUserId());
        hrDeployPlan.setLastUpdateUserName(currentUserDetail.getUserName());
        if(StringUtil.isNullOrSpace(hrDeployPlan.getId())){
            //新增
            hrDeployPlan.setId(IDHelper.uuid());
            hrDeployPlan.setCreateTime(date);
            hrDeployPlan.setCreateUser(currentUserDetail.getUserId());
            hrDeployPlan.setCreateUserName(currentUserDetail.getUserName());
            String folio = hrDeployPlan.getProcessName() + "-" + hrDeployPlan.getCreateUser() + "-" +
                    new SimpleDateFormat("yyyyMMdd").format(hrDeployPlan.getCreateTime());
            hrDeployPlan.setFolio(folio);
            hrDeployPlanMapper.insert(hrDeployPlan);

            HrProcessRecord record = new HrProcessRecord();
            record.setProcessType(hrDeployPlan.getDeployPlanType());
            record.setProcessName(hrDeployPlan.getProcessName());
            record.setFormInstId(hrDeployPlan.getId());
            record.setStartTime(date);
            record.setStartUser(currentUserDetail.getUserId());
            record.setStartUserName(currentUserDetail.getUserName());
            record.setFolio(folio);
            record.setStatus("0");
            //保存一条审批记录
            insertProcessRecord(record);
        }else{
            //更新
            hrDeployPlanMapper.updateById(hrDeployPlan);
        }


        return hrDeployPlan;

    }

    /**********************************
     * 用途说明: 审批操作（通过或驳回）
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    @Transactional
    public ApiResult submitProcess(Map<String, Object> params) throws Exception {
        // 流程除了启动环节，任意环节提交时均要保存流程实例id
        String procInstId = params.get("procInstId").toString();
        if (StringUtil.isNullOrSpace(procInstId)) {
            throw new ScpException("procInstId is missing.");
        }
        //判断是前进还是后退
        String flag = params.get("deal_answer").toString();
        ApiResult apiResult = null;
        // 根据环节名称判断当前处理逻辑
        String act_name = params.get("now_deal_act").toString();
        String formInstID = params.get("formInstID").toString();
        params.put("next_deal_name",JSONArray.parseArray(JSON.toJSONString(params.remove("next_deal_name"))));
        Object copygive = params.remove("copygive");
        if(copygive != null && !"".equals(copygive)){
            params.put("copygive",JSONArray.parseArray(JSON.toJSONString(copygive)));
        }
        if (!StringUtil.isNullOrSpace(act_name) &&
                ("020".equals(act_name) || "030".equals(act_name)
                ||"040".equals(act_name) || "050".equals(act_name)
                ||"060".equals(act_name) || "070".equals(act_name)
                        ||"010".equals(act_name))) {
            HrDeployPlan plan = new HrDeployPlan();
            plan.setId(formInstID);
            plan.setProcInstId(procInstId);
            hrDeployPlanMapper.updateById(plan);

            List<HrProcessRecord> hrProcessRecords = hrProcessRecordMapper.selectList(new QueryWrapper<HrProcessRecord>()
            .eq("form_inst_id",formInstID));
            if(hrProcessRecords != null && hrProcessRecords.size() != 0){
                HrProcessRecord record = hrProcessRecords.get(0);
                record.setCurrentAct(params.get("act_name")+"");
                record.setCurrentDealName(currentUser.getCurrentUserDetail().getUserName());
                if(  (("1".equals(record.getProcessType()) && "030".equals(act_name))
                 ||  ("2".equals(record.getProcessType()) && "070".equals(act_name)) ) && "1".equals(flag)
                ){
                    //最后一个审批环节且为通过的话，status设为1
                    record.setStatus("1");
                }
                //保存一条审批记录
                insertProcessRecord(record);
            }


            if ("1".equals(flag)) {
                //提交
                apiResult = bpmCenterService.submitworklistitem(params);
//                processAudit(params);
            } else if ("2".equals(flag)) {
                //驳回
                apiResult = bpmCenterService.rollBackAction(params);
            }
        } else {
            throw new ScpException("activity not found.");
        }
        return apiResult;
    }

    private void insertProcessRecord(HrProcessRecord record){
        Date date = new Date();
        UserInfo currentUserDetail = currentUser.getCurrentUserDetail();
        record.setLastUpdateTime(date);
        record.setLastUpdateUser(currentUserDetail.getUserId());
        record.setLastUpdateUserName(currentUserDetail.getUserName());
        //新增
        record.setId(IDHelper.uuid());
        record.setCreateTime(date);
        record.setCreateUser(currentUserDetail.getUserId());
        record.setCreateUserName(currentUserDetail.getUserName());
        hrProcessRecordMapper.insert(record);
    }

    @Override
    public HrDeployPlan getDeployPlanInfo(String id) {
        return hrDeployPlanMapper.selectOne(new QueryWrapper<HrDeployPlan>()
                .select("*"
                ,"(select file_center_file_name from tbl_common_fileupload tcf where tcf.file_center_file_id = tbl_hr_deploy_plan.plan_file_id) as plan_file_name"
                ,"(select file_center_url from tbl_common_fileupload tcf where tcf.file_center_file_id = tbl_hr_deploy_plan.plan_file_id) as plan_file_path"
                ,"(select file_center_file_name from tbl_common_fileupload tcf where tcf.file_center_file_id = tbl_hr_deploy_plan.backend_plan_file_id) as backend_plan_file_name"
                ,"(select file_center_url from tbl_common_fileupload tcf where tcf.file_center_file_id = tbl_hr_deploy_plan.backend_plan_file_id) as backend_plan_file_path"
                )
        .eq("id",id));
    }

    @Override
    public ApiResult deleteDraft(Map<String, Object> params) throws Exception {
        String planId = params.get("formno").toString();
        hrDeployPlanMapper.deleteById(planId);

        return bpmCenterService.deleteMyDraft(params);
    }
}
